package com.riven.bilibilidemo.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.riven.bilibilidemo.R;
import com.riven.bilibilidemo.adapter.SectionedRecyclerViewAdapter;
import com.riven.bilibilidemo.bean.BannerEntity;
import com.riven.bilibilidemo.bean.RegionRecommendBannerSection;
import com.riven.bilibilidemo.bean.RegionRecommendDynamicSection;
import com.riven.bilibilidemo.bean.RegionRecommendHotSection;
import com.riven.bilibilidemo.bean.RegionRecommendInfo;
import com.riven.bilibilidemo.bean.RegionRecommendNewSection;
import com.riven.bilibilidemo.bean.RegionRecommendTypesSection;
import com.riven.bilibilidemo.interfaces.BiliAppService;
import com.riven.bilibilidemo.utils.HttpUtilsOne;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class RegionTypeRecommendFragment extends Fragment {


    @BindView(R.id.recycle)
    RecyclerView recycle;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    private int rid;
    private String URL = "http://app.bilibili.com/";
    private boolean mIsRefreshing = false;

    private SectionedRecyclerViewAdapter mSectionedRecyclerViewAdapter;

    private List<BannerEntity> bannerEntities = new ArrayList<>();

    private List<RegionRecommendInfo.DataBean.BannerBean.TopBean> banners = new ArrayList<>();

    private List<RegionRecommendInfo.DataBean.RecommendBean> recommends = new ArrayList<>();

    private List<RegionRecommendInfo.DataBean.NewBean> news = new ArrayList<>();

    private List<RegionRecommendInfo.DataBean.DynamicBean> dynamics = new ArrayList<>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_region_type_recommend, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    public static RegionTypeRecommendFragment newInstance(int rid) {

        RegionTypeRecommendFragment fragment = new RegionTypeRecommendFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("RegionTypeRecommendFragment", rid);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        finishCreateView(savedInstanceState);
    }

    private void finishCreateView(Bundle savedInstanceState) {
        rid = getArguments().getInt("RegionTypeRecommendFragment");
        initRefreshLayout();
        initRecyclerView();
    }

    private void initRecyclerView() {
        mSectionedRecyclerViewAdapter = new SectionedRecyclerViewAdapter();
        GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
        mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {

            @Override
            public int getSpanSize(int position) {

                switch (mSectionedRecyclerViewAdapter.getSectionItemViewType(position)) {
                    case SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER:
                        return 2;

                    default:
                        return 1;
                }
            }
        });
        recycle.setLayoutManager(mLayoutManager);
        recycle.setAdapter(mSectionedRecyclerViewAdapter);
        setRecycleNoScroll();

    }
    private void setRecycleNoScroll() {

        recycle.setOnTouchListener((v, event) -> mIsRefreshing);
    }

    private void loadData() {
        HttpUtilsOne.getAPIServer(BiliAppService.class, URL).getRegionRecommends(rid)
                .subscribeOn(Schedulers.io())
                .map(RegionRecommendInfo::getData)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(dataBean -> {
                    banners.addAll(dataBean.getBanner().getTop());
                    recommends.addAll(dataBean.getRecommend());
                    news.addAll(dataBean.getNewX());
                    dynamics.addAll(dataBean.getDynamic());
                    finishTask();
                });

    }
    private void clearData() {

        bannerEntities.clear();
        banners.clear();
        recommends.clear();
        news.clear();
        dynamics.clear();
        mIsRefreshing = true;
        mSectionedRecyclerViewAdapter.removeAllSections();
    }
    public void finishTask() {

        converBanner();
        mSectionedRecyclerViewAdapter.addSection(new RegionRecommendBannerSection(bannerEntities));
        mSectionedRecyclerViewAdapter.addSection(new RegionRecommendTypesSection(getActivity(), rid));
        mSectionedRecyclerViewAdapter.addSection(
                new RegionRecommendHotSection(getActivity(), rid, recommends));
        mSectionedRecyclerViewAdapter.addSection(
                new RegionRecommendNewSection(getActivity(), rid, news));
        mSectionedRecyclerViewAdapter.addSection(
                new RegionRecommendDynamicSection(getActivity(), dynamics));

        mIsRefreshing = false;
        swipeRefreshLayout.setRefreshing(false);
        mSectionedRecyclerViewAdapter.notifyDataSetChanged();
    }
    private void converBanner() {

        Observable.from(banners)
                .forEach(topBean -> bannerEntities.add(new BannerEntity(topBean.getUri(),
                        topBean.getTitle(), topBean.getImage())));
    }

    private void initRefreshLayout() {
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        recycle.post(() -> {
            swipeRefreshLayout.setRefreshing(true);
            mIsRefreshing = true;
            loadData();
        });
        swipeRefreshLayout.setOnRefreshListener(() -> {
            clearData();
            loadData();
        });
    }

}
